﻿using BLL.CSocket;
using System;
using System.Configuration;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SanFangConsole
{
    class Program
    {
        static Socket socketServer = null; //服务器端的套接字，用于监听客户端连接
        static int port = int.Parse(ConfigurationManager.AppSettings["PortNumber"].ToString());
        static int maxThreadCount = int.Parse(ConfigurationManager.AppSettings["MaxThreadNumber"].ToString()); //最大线程数


        static void Main(string[] args)
        {
            socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress[] ipList = Dns.GetHostAddresses(Dns.GetHostName());
            IPAddress ip = null;
            foreach (IPAddress address in ipList)
            {
                if (address.AddressFamily != AddressFamily.InterNetwork)
                    continue;
                else
                {
                    ip = address;
                    break;
                }

            }
            EndPoint ep = new IPEndPoint(ip, port);
            socketServer.Bind(ep);
            socketServer.Listen(20);   //置于侦听状态,问题，是否在此设置最大线程数

            while (true)
            {
                try
                {
                    Socket client = socketServer.Accept();

                    ClientThread newclient = new ClientThread(client);

                    Thread thread = new Thread(new ThreadStart(newclient.Receive));

                    if (BLL.Business.Common.ThreadCount < maxThreadCount)
                    {
                        thread.Start();
                    }

                }
                catch (Exception ex)
                {

                }
            }

        }

    }
}
